// pages/order_detail/order_detail.ts

interface OrderProduct {
  id: number;
  name: string;
  desc: string;
  price: number;
  quantity: number;
  image: string;
}

interface OrderInfo {
  orderNo: string;
  createTime: string;
  payMethod: string;
  payTime?: string;
  status: string;
  totalProductPrice: number;
  discountAmount: number;
  actualAmount: number;
  product: OrderProduct;
}

interface ContactInfo {
  name: string;
  phone: string;
  idCard: string;
}

interface OrderStep {
  title: string;
  content: string;
}

Page({
  data: {
    orderId: '',
    currentStep: 1, // 当前订单进度步骤
    selectedPayment: 'wxpay', // 默认选中微信支付
    orderStatusText: '待付款',
    orderStatusDesc: '请尽快完成支付，订单将在30分钟后自动取消',
    orderSteps: [
      {
        title: '提交订单',
        content: '2023-12-05 14:30:25'
      },
      {
        title: '支付订单',
        content: '等待支付'
      },
      {
        title: '确认出票',
        content: '等待确认'
      },
      {
        title: '完成',
        content: '交易完成'
      }
    ] as OrderStep[],
    orderInfo: {
      orderNo: 'GZ20231205143025789',
      createTime: '2023-12-05 14:30:25',
      payMethod: '微信支付',
      status: 'PENDING_PAYMENT', // PENDING_PAYMENT、PAID、COMPLETED、CANCELED
      totalProductPrice: 356.00,
      discountAmount: 50.00,
      actualAmount: 306.00,
      product: {
        id: 1,
        name: '荔波小七孔景区门票',
        desc: '2023-12-10 使用 成人票 2张',
        price: 178.00,
        quantity: 2,
        image: 'https://images.unsplash.com/photo-1529822438134-3adce6a81a09'
      }
    } as OrderInfo,
    contactInfo: {
      name: '',
      phone: '',
      idCard: ''
    } as ContactInfo
  },

  onLoad: function (options: Record<string, string>) {
    // 获取订单ID并加载订单信息
    if (options.id) {
      this.setData({
        orderId: options.id
      });
      this.loadOrderDetail(options.id);
    }
  },

  // 加载订单详情
  loadOrderDetail: function (orderId: string) {
    // 这里应该是API请求获取订单详情
    // 模拟异步加载数据
    wx.showLoading({
      title: '加载中',
    });

    setTimeout(() => {
      // 模拟不同状态的订单
      if (orderId === '2') {
        // 已支付状态
        this.setData({
          orderInfo: {
            orderNo: 'GZ20231205143025789',
            createTime: '2023-12-05 14:30:25',
            payMethod: '微信支付',
            payTime: '2023-12-05 14:35:10',
            status: 'PAID',
            totalProductPrice: 356.00,
            discountAmount: 50.00,
            actualAmount: 306.00,
            product: {
              id: 1,
              name: '荔波小七孔景区门票',
              desc: '2023-12-10 使用 成人票 2张',
              price: 178.00,
              quantity: 2,
              image: 'https://images.unsplash.com/photo-1529822438134-3adce6a81a09'
            }
          },
          contactInfo: {
            name: '张三',
            phone: '13800138000',
            idCard: '52010119900101****'
          },
          orderStatusText: '待使用',
          orderStatusDesc: '门票将于2023-12-10生效，请按时使用',
          currentStep: 2,
          orderSteps: [
            {
              title: '提交订单',
              content: '2023-12-05 14:30:25'
            },
            {
              title: '支付订单',
              content: '2023-12-05 14:35:10'
            },
            {
              title: '确认出票',
              content: '等待确认'
            },
            {
              title: '完成',
              content: '交易完成'
            }
          ]
        });
      } else if (orderId === '3') {
        // 已完成状态
        this.setData({
          orderInfo: {
            orderNo: 'GZ20231201123025789',
            createTime: '2023-12-01 12:30:25',
            payMethod: '微信支付',
            payTime: '2023-12-01 12:35:10',
            status: 'COMPLETED',
            totalProductPrice: 356.00,
            discountAmount: 50.00,
            actualAmount: 306.00,
            product: {
              id: 1,
              name: '荔波小七孔景区门票',
              desc: '2023-12-03 使用 成人票 2张',
              price: 178.00,
              quantity: 2,
              image: 'https://images.unsplash.com/photo-1529822438134-3adce6a81a09'
            }
          },
          contactInfo: {
            name: '张三',
            phone: '13800138000',
            idCard: '52010119900101****'
          },
          orderStatusText: '已完成',
          orderStatusDesc: '您的订单已完成，感谢您的使用',
          currentStep: 3,
          orderSteps: [
            {
              title: '提交订单',
              content: '2023-12-01 12:30:25'
            },
            {
              title: '支付订单',
              content: '2023-12-01 12:35:10'
            },
            {
              title: '确认出票',
              content: '2023-12-01 12:40:25'
            },
            {
              title: '完成',
              content: '2023-12-03 10:15:30'
            }
          ]
        });
      } else if (orderId === '4') {
        // 已取消状态
        this.setData({
          orderInfo: {
            orderNo: 'GZ20231204153025789',
            createTime: '2023-12-04 15:30:25',
            payMethod: '-',
            status: 'CANCELED',
            totalProductPrice: 356.00,
            discountAmount: 50.00,
            actualAmount: 306.00,
            product: {
              id: 1,
              name: '荔波小七孔景区门票',
              desc: '2023-12-15 使用 成人票 2张',
              price: 178.00,
              quantity: 2,
              image: 'https://images.unsplash.com/photo-1529822438134-3adce6a81a09'
            }
          },
          contactInfo: {
            name: '张三',
            phone: '13800138000',
            idCard: '52010119900101****'
          },
          orderStatusText: '已取消',
          orderStatusDesc: '订单已取消',
          currentStep: 0,
          orderSteps: [
            {
              title: '提交订单',
              content: '2023-12-04 15:30:25'
            },
            {
              title: '订单取消',
              content: '2023-12-04 16:00:00'
            }
          ]
        });
      }
      
      wx.hideLoading();
    }, 500);
  },

  // 复制订单号
  copyOrderNo: function () {
    wx.setClipboardData({
      data: this.data.orderInfo.orderNo,
      success: function () {
        wx.showToast({
          title: '订单号已复制',
          icon: 'success'
        });
      }
    });
  },

  // 支付方式变更
  onPaymentChange: function (e: any) {
    this.setData({
      selectedPayment: e.detail.value
    });
  },

  // 联系人姓名变更
  onNameChange: function (e: any) {
    this.setData({
      'contactInfo.name': e.detail.value
    });
  },

  // 联系人手机变更
  onPhoneChange: function (e: any) {
    this.setData({
      'contactInfo.phone': e.detail.value
    });
  },

  // 联系人身份证变更
  onIdCardChange: function (e: any) {
    this.setData({
      'contactInfo.idCard': e.detail.value
    });
  },

  // 支付订单
  onPayOrder: function () {
    // 检查联系人信息是否填写完整
    const { name, phone, idCard } = this.data.contactInfo;
    if (!name || !phone || !idCard) {
      wx.showToast({
        title: '请填写完整联系人信息',
        icon: 'none'
      });
      return;
    }

    // 模拟支付流程
    wx.showLoading({
      title: '正在支付',
    });

    setTimeout(() => {
      wx.hideLoading();
      
      // 根据支付方式执行不同的支付逻辑
      if (this.data.selectedPayment === 'wxpay') {
        // 调用微信支付接口
        wx.showModal({
          title: '支付提示',
          content: '模拟微信支付流程，实际开发需接入微信支付API',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              this.onPaySuccess();
            }
          }
        });
      } else if (this.data.selectedPayment === 'alipay') {
        // 支付宝支付逻辑
        wx.showModal({
          title: '支付提示',
          content: '模拟支付宝支付流程，实际开发需接入支付宝支付SDK',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              this.onPaySuccess();
            }
          }
        });
      } else if (this.data.selectedPayment === 'balance') {
        // 余额支付逻辑
        wx.showModal({
          title: '支付提示',
          content: '模拟余额支付流程，实际开发需检查账户余额',
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              this.onPaySuccess();
            }
          }
        });
      }
    }, 1000);
  },

  // 支付成功回调
  onPaySuccess: function () {
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 2000
    });

    // 更新订单状态
    setTimeout(() => {
      this.setData({
        'orderInfo.status': 'PAID',
        'orderInfo.payMethod': this.data.selectedPayment === 'wxpay' ? '微信支付' : 
                              (this.data.selectedPayment === 'alipay' ? '支付宝' : '余额支付'),
        'orderInfo.payTime': this.formatTime(new Date()),
        orderStatusText: '待使用',
        orderStatusDesc: '门票将于2023-12-10生效，请按时使用',
        currentStep: 2,
        orderSteps: [
          {
            title: '提交订单',
            content: this.data.orderSteps[0].content
          },
          {
            title: '支付订单',
            content: this.formatTime(new Date())
          },
          {
            title: '确认出票',
            content: '等待确认'
          },
          {
            title: '完成',
            content: '交易完成'
          }
        ]
      });
    }, 500);
  },

  // 查看票据详情
  onViewDetail: function () {
    wx.navigateTo({
      url: '/pages/ticket_detail/ticket_detail?id=' + this.data.orderId
    });
  },

  // 再次购买
  onRebuy: function () {
    // 跳转到商品详情页
    wx.navigateTo({
      url: '/pages/product_detail/product_detail?id=' + this.data.orderInfo.product.id
    });
  },

  // 评价
  onReview: function () {
    wx.navigateTo({
      url: '/pages/review/review?id=' + this.data.orderId
    });
  },

  // 取消订单
  onCancelOrder: function () {
    wx.showModal({
      title: '取消订单',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '处理中',
          });

          setTimeout(() => {
            wx.hideLoading();
            
            this.setData({
              'orderInfo.status': 'CANCELED',
              orderStatusText: '已取消',
              orderStatusDesc: '订单已取消',
              currentStep: 0,
              orderSteps: [
                {
                  title: '提交订单',
                  content: this.data.orderSteps[0].content
                },
                {
                  title: '订单取消',
                  content: this.formatTime(new Date())
                }
              ]
            });

            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
          }, 1000);
        }
      }
    });
  },

  // 格式化时间
  formatTime: function (date: Date): string {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return [year, month, day].map(this.formatNumber).join('-') + ' ' + 
           [hour, minute, second].map(this.formatNumber).join(':');
  },

  formatNumber: function (n: number): string {
    const s = n.toString();
    return s[1] ? s : '0' + s;
  }
}) 